<?php
/**
 * author:歪妻
 * Date: 2020/11/9 0009
 */

require_once 'lib/common.php';
require_once 'lib/edit-post.php';
require_once 'lib/view-post.php';
session_start();
//如果不登录直接跳转到首页
if (!isLoggedIn()){
    redirectAndExit('index.php');
}
//默认空的设置
$title = $body = '';
// 初始化数据库并获取句柄
$pdo = getPDO();

$postId = null;
if (isset($_GET['post_id'])){
    $post = getView($pdo, $_GET['post_id']);
    if ($post)
    {
        $postId = $_GET['post_id'];
        $title = $post['title'];
        $body = $post['body'];
    }
}

//在这里处理后期操作
$errors = array();
if ($_POST)
{
    // 首先验证这些
    $title = $_POST['post-title'];
    if (!$title){
        $errors[] = '标题不能为空';
    }
    $body = $_POST['post-body'];
    if (!$body){
        $errors[] = '帖子内容不能为空';
    }
    if (!$errors){
        $pdo = getPDO();
        // 确定我们是否正在编辑或添加
        if ($postId)
        {
            editPost($pdo, $title, $body, $postId);
        }
        else
        {
            $userId = getAuthUserId($pdo);
            $postId = addPost($pdo, $title, $body, $userId);
            if ($postId === false)
            {
                $errors[] = '添加错误';
            }
        }
        redirectAndExit('edit-post.php?post_id=' . $postId);
    }
}
?>
<!DOCTYPE html>
<html>
    <head>
        <title>A blog application | New post</title>
        <?php require 'templates/head.php' ?>
    </head>
    <body>
    <?php require 'templates/title.php' ?>
    <?php if (isset($_GET['post_id'])): ?>
        <h1>更改帖子</h1>
    <?php else: ?>
        <h1>新建帖子</h1>
    <?php endif ?>
    <?php if ($errors): ?>
            <div class="error box">
                <ul>
                    <?php foreach ($errors as $error): ?>
                        <li><?php echo $error ?></li>
                    <?php endforeach ?>
                </ul>
            </div>
        <?php endif ?>
        <form method="post" class="post-form user-form">
            <div>
                <label for="post-title">标题:</label>
                <input id="post-title" name="post-title" type="text" value="<?php echo htmlEscape($title)?>"/>
            </div>
            <div>
                <label for="post-body">内容:</label>
                <textarea id="post-body" name="post-body" rows="12" cols="70"><?php echo htmlEscape($body) ?></textarea>
            </div>
            <div>
                <input type="submit" value="保存帖子"/>
                <a href="index.php">取消</a>
            </div>
        </form>
    </body>
</html>